<template>
  <view class="container">
    <!-- 游戏状态显示 -->
    <view class="status">
      <text>{{ gameStatus }}</text>
    </view>

    <!-- 难度选择器 -->
    <view class="difficulty">
      <picker @change="onDifficultyChange" :value="difficultyIndex" :range="difficulties">
        <view class="picker">
          难度: {{ difficulties[difficultyIndex] }}
        </view>
      </picker>
    </view>

    <!-- 游戏棋盘 -->
    <view class="board">
      <view class="row" v-for="(row, i) in board" :key="i">
        <view 
          class="cell" 
          v-for="(cell, j) in row" 
          :key="j"
          @tap="onCellTap(i, j)"
        >
          <text v-if="cell === 0" class="fruit">🍌</text>
          <text v-if="cell === 1" class="fruit">🍎</text>
        </view>
      </view>
    </view>

    <!-- 重新开始按钮 -->
    <button class="restart" @tap="restartGame">重新开始</button>

    <!-- 分数显示 -->
    <view class="score">
      <text>玩家: {{ playerScore }} </text>
      <text>电脑: {{ computerScore }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      board: [
        [null, null, null],
        [null, null, null], 
        [null, null, null]
      ],
      isPlayerTurn: true,
      gameOver: false,
      difficulties: ['简单', '中等', '困难'],
      difficultyIndex: 1,
      playerScore: 0,
      computerScore: 0
    }
  },

  computed: {
    gameStatus() {
      if (this.gameOver) {
        return this.winner === 0 ? '恭喜你赢了!' : '电脑赢了!'
      }
      return this.isPlayerTurn ? '轮到你下棋' : '电脑思考中...'
    },
    
    // 将棋盘转换为一维数组,用于API调用
    boardArray() {
      return this.board.flat()
    }
  },

  methods: {
    async onCellTap(row, col) {
      // 如果格子已被占用或不是玩家回合则返回
      if (this.board[row][col] !== null || !this.isPlayerTurn || this.gameOver) {
        return
      }

      // 玩家下棋
      this.board[row][col] = 0
      
      // 检查是否获胜
      if (this.checkWinner()) {
        this.gameOver = true
        this.playerScore++
        return
      }

      // 切换到电脑回合
      this.isPlayerTurn = false

      // 调用AI接口获取下一步
      try {
        const response = await this.getAIMove()
        const nextMove = response.data.position
        
        // 延迟一下让动画更自然
        setTimeout(() => {
          const row = Math.floor(nextMove / 3)
          const col = nextMove % 3
          this.board[row][col] = 1

          if (this.checkWinner()) {
            this.gameOver = true
            this.computerScore++
          } else {
            this.isPlayerTurn = true
          }
        }, 500)
      } catch (error) {
        console.error('AI接口调用失败:', error)
        // 降级到随机走棋
        this.randomMove()
      }
    },

    async getAIMove() {
      const difficulty = ['easy', 'medium', 'hard'][this.difficultyIndex]
      
      return await uni.request({
        url: 'https://api.sancns.com/xcx/jjGame',
        method: 'POST',
        data: {
          board: this.boardArray,
          difficulty
        }
      })
    },

    randomMove() {
      const emptyCells = []
      this.board.forEach((row, i) => {
        row.forEach((cell, j) => {
          if (cell === null) {
            emptyCells.push([i, j])
          }
        })
      })
      
      if (emptyCells.length > 0) {
        const [row, col] = emptyCells[Math.floor(Math.random() * emptyCells.length)]
        this.board[row][col] = 1
        this.isPlayerTurn = true
      }
    },

    checkWinner() {
      // 检查行
      for (let i = 0; i < 3; i++) {
        if (this.board[i][0] !== null &&
            this.board[i][0] === this.board[i][1] &&
            this.board[i][0] === this.board[i][2]) {
          return true
        }
      }

      // 检查列
      for (let j = 0; j < 3; j++) {
        if (this.board[0][j] !== null &&
            this.board[0][j] === this.board[1][j] &&
            this.board[0][j] === this.board[2][j]) {
          return true
        }
      }

      // 检查对角线
      if (this.board[0][0] !== null &&
          this.board[0][0] === this.board[1][1] &&
          this.board[0][0] === this.board[2][2]) {
        return true
      }
      
      if (this.board[0][2] !== null &&
          this.board[0][2] === this.board[1][1] &&
          this.board[0][2] === this.board[2][0]) {
        return true
      }

      return false
    },

    onDifficultyChange(e) {
      this.difficultyIndex = e.detail.value
    },

    restartGame() {
      this.board = [
        [null, null, null],
        [null, null, null],
        [null, null, null]
      ]
      this.isPlayerTurn = true
      this.gameOver = false
    }
  }
}
</script>

<style>
.container {
  padding: 20px;
  text-align: center;
}

.status {
  font-size: 20px;
  margin-bottom: 20px;
}

.difficulty {
  margin-bottom: 20px;
}

.board {
  display: inline-block;
  background: #fff;
  padding: 10px;
  border-radius: 8px;
}

.row {
  display: flex;
}

.cell {
  width: 80px;
  height: 80px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
}

.fruit {
  font-size: 40px;
}

.restart {
  margin-top: 20px;
  background: #4CAF50;
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
}

.score {
  margin-top: 20px;
  font-size: 18px;
}

.score text {
  margin: 0 10px;
}
</style>
